import { MciButton, MciNotification } from '@/components/base';
import { ElUpload } from 'element-plus';
// 下载
import { TOKEN_STORAGE_KEY } from '@/constants/config';
import { downloadFile } from '@/utils/file';
// 上传
import storage from '@/utils/storage';
import config from '@/config';
import axios from 'axios';
import '../../index.scss';

export const BatchTest = defineComponent({
  props: {
    flowId: {
      type: String,
      default: ''
    }
  },
  setup(props, context) {
    const fileList = ref([]);

    const uploadFile = () => {
      return new Promise(async (resolve, reject) => {
        if (fileList.value && fileList.value.length) {
          const file = fileList.value[0]?.raw;
          if (file) {
            try {
              const formData = new FormData();
              formData.append('flowId', props.flowId);
              formData.append('file', file);

              const uploadUrl = `${config.apiDomain}/decision-flow/testBatch`;
              // 调用后端上传接口
              const response = await axios.post(uploadUrl, formData, {
                headers: {
                  Authorization: `Bearer ${storage.get(TOKEN_STORAGE_KEY)}`, // 如果需要的话添加认证信息
                  'Content-Type': 'multipart/form-data'
                }
              });
              // 处理后端返回结果
              if (response.status === 200 && response.data.code === 0) {
                console.log('上传成功', response.data);
                resolve({ status: 'success', message: '上传成功', data: response.data });
              } else {
                console.error('上传失败', response.statusText);
                MciNotification.warning({ message: response.statusText || response.data.msg });
                reject('上传失败');
              }
            } catch (error) {
              console.error('上传过程中发生错误', error);
              MciNotification.warning({ message: error });
              reject('上传失败');
            }
          } else {
            resolve({ status: 'warning', message: '请上传文件' });
          }
        } else {
          resolve({ status: 'warning', message: '请上传文件' });
        }
      });
    };

    const onClickDownLoad = async () => {
      if (props.flowId) {
        const downUrl = `${config.apiDomain}/decision-flow/testTemplate?flowId=${props.flowId}`;
        downloadFile(downUrl);
      }
    };

    context.expose({ uploadFile });

    return () => {
      return (
        <div class="batch-test p-16">
          <div>
            <h3>
              <span class="circle">1</span>下载Excel模板
            </h3>
            <p class="mt-16 mb-16 text-gray-400">下载Excel模板，批量填写信息</p>
            <MciButton class="mb-20" onClick={onClickDownLoad}>
              <i class="mci-icon-download1"></i>下载
            </MciButton>
          </div>
          <div>
            <h3>
              <span class="circle">2</span>上传已编辑Excel
            </h3>
            <ElUpload fileList={fileList} class="upload-demo" limit={1} accept={'.xlsx,.xls'} drag={false} auto-upload={false}>
              {{
                default() {
                  return <div></div>;
                },
                trigger() {
                  return (
                    <>
                      <MciButton class="mt-16" type="primary">
                        <i class="mci-icon-cloud-download"></i>上传文件
                      </MciButton>
                    </>
                  );
                },
                tip() {
                  return (
                    <>
                      <div class="el-upload__tip">限制上传1个文件</div>
                    </>
                  );
                }
              }}
            </ElUpload>
          </div>
        </div>
      );
    };
  }
});
